import json
import os


class FreeLabelFormat(object):

    suffix = ".json"

    def __init__(self) -> None:
        self.shapes = []
        self.categories = "categories.json"

    def writeCategoriesFile(self, save_path, save_info):
        categories_file = os.path.join(save_path, self.categories)
        with open(categories_file, 'w') as f:
            json.dump(save_info, f, indent=4)

    def readCategoriesFile(self, file_path):
        categories_file = os.path.join(file_path, self.categories)
        data = None
        if os.path.exists(categories_file):

            with open(categories_file) as obj:
                data = json.load(obj)
        return data

    def read(self, filename, image_size):
        """加载标签"""
        with open(filename, "r") as obj:
            data = json.load(obj)
            self.shapes = data

    def write(self, filename, shapes, image_w, image_h):
        """保存标签数据"""
        with open(filename, "w") as obj:
            json.dump(shapes, obj, indent=4)
        self.shapes = shapes

    def is_label_file(self, filename):
        """是否是标签文件"""
        return os.path.splitext(filename)[0].lower() == FreeLabelFormat.suffix
